<!-- 
 * @Description:
 * @Date: 2024-06-25 21:24:10
 * @LastEditTime: 2024-07-04 08:45:36
-->
<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '答题',
  },
}
</route>
<template>
  <view class="bg-#f6f6f6 overflow-auto w-100% h-screen box-border p-20rpx">
    <view v-for="(question, index) in AnswerList" :key="question.id" class="bg-#fff p-20rpx">
      <view class="flex items-center mb-18rpx">
        <view class="topic mr-18rpx">题目{{ numberfilter(index + 1) }}</view>
        <view v-if="notAnswered[index]" class="flex items-center">
          <view><wd-icon name="error-circle-filled" size="28rpx" color="#BC0D0D"></wd-icon></view>
          <view class="no-answer ml-20rpx">未作答</view>
        </view>
      </view>
      <view class="question">{{ question.questionText }}</view>

      <wd-checkbox-group v-model="checked[index]" cell shape="square">
        <wd-checkbox modelValue="A" shape="square">A.{{ question.optionA }}</wd-checkbox>
        <wd-checkbox modelValue="B" shape="square">B.{{ question.optionB }}</wd-checkbox>
        <wd-checkbox modelValue="C" shape="square">C.{{ question.optionC }}</wd-checkbox>
        <wd-checkbox modelValue="D" shape="square">D.{{ question.optionD }}</wd-checkbox>
      </wd-checkbox-group>
    </view>
  </view>
  <view class="question-btn flex items-center justify-between">
    <wd-button plain hairline @click="handleSubmit">提交</wd-button>
  </view>
</template>

<script lang="ts" setup>
import { getAnswer, submitAnswer } from '@/service/partBuilding/index'
import { useToast } from 'wot-design-uni'
const toast = useToast()
const AnswerList = ref([])
const optionsId = ref()
const saveId = ref()
const checked = ref(Array.from({ length: AnswerList.value.length }, () => []))
const notAnswered = ref(Array.from({ length: AnswerList.value.length }, () => true))
watch(
  () => checked.value,
  (val) => {},
  { immediate: true },
)
// 提交答案
const answers = ref([])
async function handleSubmit() {
  let allAnswered = true
  answers.value = []
  for (let index = 0; index < AnswerList.value.length; index++) {
    const selectedAnswers = checked.value[index] || []

    if (selectedAnswers.length === 0) {
      allAnswered = false
      notAnswered.value[index] = true
      continue
    }
    notAnswered.value[index] = false
    answers.value.push({
      userId: saveId.value,
      questionId: AnswerList.value[index].id,
      selectedAnswers,
    })
  }
  if (!allAnswered) {
    toast.error({
      msg: '所有题目都必须作答后才能提交。',
    })
    return
  }
  try {
    const data = await submitAnswer(answers.value, { materialId: Number(optionsId.value) })
    if (data) {
      toast.success({
        msg: '提交成功',
      })
      checked.value = Array.from({ length: AnswerList.value.length }, () => [])
      uni.navigateTo({ url: '/pages/PartyBuilding/index' })
    }
  } catch (error) {
    console.error('提交失败:', error)
    toast.error({
      msg: '提交失败，请稍后再试。',
    })
  }
}
// 将1改为一
const numberfilter = (num) => {
  const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  const unit = ['', '十', '百']
  num = parseInt(num)
  const getWan = (temp) => {
    const strArr = temp.toString().split('').reverse() // reverse()反转元素顺序
    let newNum = ''
    for (let i = 0; i < strArr.length; i++) {
      newNum =
        (i === 0 && strArr[i] === 0
          ? ''
          : i > 0 && strArr[i] === 0 && strArr[i - 1] === 0
            ? ''
            : changeNum[strArr[i]] + (strArr[i] === 0 ? unit[0] : unit[i])) + newNum
    }
    return newNum
  }
  const overWan = Math.floor(num / 100)
  let noWan = num % 100
  if (noWan.toString().length < 2) noWan = '0' + noWan
  return overWan ? getWan(overWan) + '百' + getWan(noWan) : getWan(num)
}

onLoad(async (options) => {
  optionsId.value = options.id
  const params = reactive({
    pageNo: 1,
    pageSize: 100,
    materialId: options.id,
  })

  const data: any = await getAnswer({ ...params })
  AnswerList.value = data.data.list
  uni.getStorageInfo({
    success: function () {
      // 单独获取 'user' 键的值
      uni.getStorage({
        key: 'user',
        success: function (res) {
          const data = JSON.parse(res.data)
          saveId.value = data.userInfo.residentId
        },
        fail: function (err) {
          console.error('获取 user 失败:', err)
        },
      })
    },
  })
})
</script>
<style lang="scss">
.topic {
  font-size: 28rpx;
  line-height: 48rpx;
  color: rgba(27, 27, 27, 1);
  text-align: justify;
}
.topic::before {
  height: 48rpx;
  margin-right: 20rpx;
  content: '';
  border-left: 8rpx solid #d71818;
}
.question {
  margin-right: 20rpx;
  font-size: 28rpx;
  line-height: 48rpx;
  color: rgba(27, 27, 27, 1);
  text-align: justify;
}
::v-deep.wd-button.is-plain.is-primary {
  width: 100%;
  color: #fff !important;
  background: #d71818 !important;
  border: none !important;
  border-radius: 18rpx !important;
}
.fixed-button {
  position: fixed;
  bottom: 0;
  left: 50%;
  z-index: 99;
  width: 100%;
  transform: translateX(-50%);
}
.question-btn {
  height: 100rpx;
  padding: 40rpx !important;
  text-align: center;
  box-shadow: 0px -3px 6px 0px rgba(201, 201, 201, 0.4);
}
.no-answer {
  font-size: 28rpx;
  line-height: 33px;
  color: rgba(188, 13, 13, 1);
  text-align: left;
}
::v-deep.wd-checkbox.is-checked .wd-checkbox__shape {
  background: #d71818 !important;
  border-color: #d71818 !important;
  width: 14px !important;
  height: 14px !important;
}
::v-deep.wd-checkbox__txt {
  white-space: normal !important;
}
::v-deep.wd-checkbox.is-cell-box {
  display: flex !important;
}
::v-deep.wd-checkbox__shape.is-square {
  top: 6rpx;
}
::v-deep.wd-checkbox__txt {
  width: 560rpx !important;
  text-align: justify !important;
}
::v-deep.wd-checkbox__shape {
  width: var(--wot-checkbox-size, 14px) !important;
  height: var(--wot-checkbox-size, 14px) !important ;
}
</style>
